#include "Encoding.h"

DBCSEncoding::DBCSEncoding( EncodingCodePage codePage ) : m_codePage(codePage)
{

}

int32 DBCSEncoding::GetCharSize( uint32& charSize )
{
	charSize = 1;
	return R_SUCCEED;
}

int32 DBCSEncoding::GetByteSize(  uint32& byteSize  )
{
	byteSize = 2;
	return R_SUCCEED;
}

int32 DBCSEncoding::Decode( cbyte* bytes , uint32 byteSize , tchar* chars , uint32 charSize , uint32& useCharSize , uint32& useByteSize )
{
	int32 code = R_SUCCEED;

	uint32 uCharSize = 0;

	cbyte*  search = bytes + byteSize;

	while( (search > bytes ) ) 
	{
		search--;
		if(  *search < 0x80  )
		{
			search++;
			break;
		}
	}

	if(  (( (bytes + byteSize) - search ) %2 )!= 0 )
		byteSize-=1;

	DWORD cnvSize = ::MultiByteToWideChar( m_codePage , NULL , (LPCSTR)bytes,byteSize,chars, charSize );

	if( cnvSize == 0 )
	{
		code = GetCharSize( useCharSize );
		if( code != R_SUCCEED )
			return code;
		return E_ENCODING_MTOW;
	}

	useByteSize = byteSize;
	useCharSize = cnvSize;

	return R_SUCCEED;
}

int32 DBCSEncoding::Encode( ctchar* chars , uint32 charSize , byte* bytes , uint32 byteSize , uint32& useCharSize , uint32& useByteSize )
{
	int32 code = R_SUCCEED;

	DWORD cvtSize = ::WideCharToMultiByte( DEFAULT_CODE_PAGE , NULL , chars , charSize , (LPSTR)bytes , byteSize , NULL , NULL );

	if( cvtSize == 0 )
	{
		code = GetByteSize( useByteSize );
		if(code != R_SUCCEED)
			return code;
		return E_ENCODING_WTOM;
	}

	useByteSize = cvtSize;
	useCharSize = charSize;

	return R_SUCCEED;
}

int32 DBCSEncoding::GetCodePage( EncodingCodePage& codePage )
{
	codePage = m_codePage;
	return R_SUCCEED;
}

int32 DBCSEncoding::GetPeramble( byte* bytes , cuint32& byteSize )
{
	return R_SUCCEED;
}

int32 DBCSEncoding::GetPerambleSize( uint32& perambleSize )
{
	perambleSize = 0;
	return R_SUCCEED;
}